<?php

namespace Library;

class Picture {

	private $_image;
	private $_tmpName;
	private $_name;
	
	private $_dims = array(
		'width' => 200,
		'height' => 200
	);

	
	public function __construct( $content ) {
		
		try {
			$this->_image = $image = new \Imagick();
			$success = $image->readImageBlob( $content );
			unset( $content );
			if( !$success ) {
				throw new \Exception( 'Invalid image' );
			}
		}
		catch( \ImagickException $e ) {
			throw new \Exception( 'Invalid image' );
		}
	}
	
	public function getTmpName() {
		if( $this->_tmpName === null ) {
			$this->_tmpName = $tmpName = $this->_getTmpName();
			$this->_resizeTmpImage();
			$this->_saveTmpImage( $tmpName );
		}
		return $this->_tmpName;
	}
	
	public function save( $left, $top, $width ) {
		if( $this->_name === null ) {
			$this->_name = $this->_getName(); 
			$this->_saveTo( 'profile' );
			$this->_image->cropImage( $width, $width, $left, $top );
			$this->_image->scaleImage( 50, 50, true );
			$this->_saveTo( '50x50' );
			$this->_image->scaleImage( 32, 32, true );
			$this->_saveTo( '32x32' );
			$this->_image->scaleImage( 16, 16, true );
			$this->_saveTo( '16x16' );
		}
		return $this->_name;
	}
	
	private function _saveTo( $path ) {
		$this->_image->writeImage( $this->_getPath( $path ) );
	}
	
	private function _getPath( $path ) {
		$conf = \Library\Config::get( 'path' );
		return $conf['public'] . '/' . $conf['images']['users'] . '/' . $path . '/' . $this->_name . '.jpg';
	}
	
	private function _saveTmpImage( $tmpName ) {
		$conf = \Library\Config::get( 'path' );
		$this->_image->writeImage( $conf['public'] . '/' . $tmpName );
		return $this;
	}
	
	private function _resizeTmpImage() {
		$this->_image->scaleImage( $this->_dims['width'], $this->_dims['height'], true );
		return $this;
	}
	
	private function _getTmpName() {
	
		$conf = \Library\Config::get( 'path' );
		return $this->_getRandomName( $conf['images']['tmp'] );
	}
	
	private function _getName() {
	
		$conf = \Library\Config::get( 'path' );
		return $this->_getRandomName( $conf['images']['users'] . '/profile/', true );
	}
	
	private function _getRandomName( $path, $nameOnly = false ) {
		$i = 1000;
		$name = '';
		do {
			$rand = md5(openssl_random_pseudo_bytes( 30 ));
			$name = $rand;
			$filename = $path . "/" . $name . '.jpg';
			$file = $conf['public'] . '/' . $filename;
			$fp = @fopen( $file, 'x' );
			$i--;
		} 
		while(!$fp && $i); 
		if( $i ) {
			fclose($fp);
		} 
		
		return $nameOnly ? $name : $filename;
	}

}

